do "E:\yungyu\lottery_baby\do\set_environment.do"

************************** 1. lottery_record **************************

capture log close
log using "$log\2.1.lottery_record_`c(current_date)'.log" , replace
clear
set more off

** Find winners and their spouse (at t-1)
use "$wdata\all_winner_3types_nonsprt_93109.dta"
keep if inrange(year,96,108) //Current winner = 96 to 101; future winner = 103 to 108
gen real_win_year = year
rename pers_idn idn
merge m:1 idn using "$public\observation\real_jhq_v2.dta" //Personal characteristics
keep if _m == 3
drop _m
foreach x in idn born_year death_year gender{
	rename `x' pers_`x'
}

replace year = real_win_year - 1 //Spouse of t-1

forv i = 95(1)107{
	dis "Merge couple of year `i'..."
	merge 1:1 pers_idn year using "$public\couple\couple_`i'.dta", update
	drop if _m==2
	drop _m pair_idn
}

rename couple_idn idn 
merge m:1 idn using "$public\observation\real_jhq_v2.dta" //Spouse characteristics
drop if _m == 2
drop _m
foreach x in idn born_year death_year gender{
	rename `x' spouse_`x'
}

keep if pers_gender == 1 | pers_gender == 2

gen current = inrange(real_win_year,96,101)
gen future = inrange(real_win_year,103,108)

replace year = real_win_year //Lottery year
rename year win_year
replace win_year = win_year - 7 if future == 1 //Pseudo win year

keep real_win_year win_year pers_idn pers_born_year pers_death_year pers_gender spouse_idn spouse_born_year spouse_death_year spouse_gender current future
duplicates drop

**Get past record on prize amount
expand 16 //93 to 108
sort real_win_year pers_idn 
by real_win_year pers_idn: gen year = 92 +_n

merge m:1 pers_idn year using "$wdata\all_winner_3types_nonsprt_93109.dta"
drop if _m == 2
drop _m
rename payment pers_prize
replace pers_prize = 0 if pers_prize == .
rename pers_idn idn

rename spouse_idn pers_idn
merge m:1 pers_idn year using "$wdata\all_winner_3types_nonsprt_93109.dta"
drop if _m == 2
drop _m
rename payment spouse_prize
replace spouse_prize = 0 if spouse_prize == .
rename pers_idn spouse_idn
rename idn pers_idn 

drop if pers_prize == 0 & spouse_prize == 0 //Drop if both have no prize

**adjusted wit CPI 
merge m:1 year using "$wdata/cpi.dta", noreport
drop if _m == 2
drop cpi_sy _merge
foreach x in "pers" "spouse" {
	foreach y in "prize"{
		dis "adjust `x's' `y' by cpi..."
		gen `x'_real_`y' = `x'_`y'/cpi*100
		gen `x'_real_`y'_aftertax = `x'_real_`y' * 0.8
	}
}

sort pers_idn win_year year

order current future win_year real_win_year pers_idn spouse_idn year cpi pers_prize spouse_prize pers_real_prize spouse_real_prize pers_real_prize_aftertax spouse_real_prize_aftertax pers_gender pers_born_year pers_death_year spouse_gender spouse_born_year spouse_death_year

save "$wdata\individual_winners.dta", replace

log close
